package org.zstacks.znet.codec;

import java.io.Closeable;
import java.io.IOException;
import java.nio.channels.ServerSocketChannel;

import org.zstacks.znet.Helper;
import org.zstacks.znet.log.Logger;
import org.zstacks.znet.nio.Dispatcher;
import org.zstacks.znet.nio.Session;

public class StringServer extends StringAdaptor implements Closeable{  
	private static final Logger log = Logger.getLogger(StringServer.class); 

	protected Dispatcher dispatcher;
	protected String host = "0.0.0.0";
	protected int port;
	protected final String serverAddr;
	protected String serverName = "StringServer";
	protected ServerSocketChannel serverChannel;
	
	public StringServer(int port, Dispatcher dispatcher) { 
		this("0.0.0.0", port, dispatcher);
	}
	
	public StringServer(String host, int port, Dispatcher dispatcher) { 
		this.dispatcher = dispatcher;
		this.host = host;
		this.port = port; 
		//
		this.dispatcher.serverIoAdaptor(this);
		
	  	if("0.0.0.0".equals(this.host)){
    		this.serverAddr = String.format("%s:%d", Helper.getLocalIp(), this.port);
    	} else {
    		this.serverAddr = String.format("%s:%d", this.host, this.port);
    	}
		
	}
	

    public void onMessage(Object obj, Session sess) throws IOException {  
    	sess.write(obj);
    }  
    
    public void start() throws IOException{  
    	if(serverChannel != null){
    		log.info("server already started");
    		return;
    	}
    	if(!this.dispatcher.isStarted()){
			this.dispatcher.start();
		}
    	serverChannel = dispatcher.registerServerChannel(host, port);
    	log.info("%s serving@%s:%d", this.serverName, this.host, this.port);
    }
    
    @Override
    public void close() throws IOException { 
    	if(serverChannel != null){
    		serverChannel.close();
    	}
    }
    
    @SuppressWarnings("resource")
	public static void main(String[] args) throws Exception {   
		int selectorCount = Helper.option(args, "-selector", 2);
		int executorCount = Helper.option(args, "-executor", 32);
		
		Dispatcher dispatcher = new Dispatcher()
			.selectorCount(selectorCount)   //Selector线程数配置
			.executorCount(executorCount); //Message后台处理线程数配置
		
		StringServer server = new StringServer(80, dispatcher);
    	server.start();
		
    	//dispatcher.close(); 
	}
}

